package il.ac.braude.sona.ocsf.server;

import il.ac.braude.sona.database.User;
import il.ac.braude.sona.ocsf.Mssg;
import il.ac.braude.sona.ocsf.P;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;


public class Server extends AbstractServer {
	private DatabaseController dc;
	private HashMap<ConnectionToClient, User> usersHash = new HashMap<ConnectionToClient, User>();
	public Server(int port) {
		super(port);
		dc = DatabaseController.getInstance();
	}

	@Override
	protected void handleMessageFromClient(Object msg, ConnectionToClient client) {
		
		try {
			Mssg mssg = (Mssg) msg;
			if (mssg.equals(P.login)) 
				handleLogin(client,mssg);
			else if (mssg.equals(P.view))
				handleViewRequest(client,mssg);
			else if (mssg.equals(P.create))
				handleCreateRequest(client,mssg);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}





	private void handleLogin(ConnectionToClient c, Mssg mssg) throws IOException {
		Mssg response = mssg;
		try {
			User u = dc.login((ArrayList<String>)mssg.getMessege());
			if (u == null) response = new Mssg(mssg.getID(),P.error,"login info is incorrect.");
			else {
				usersHash.put(c, u);
				mssg.setMessege(u);
			}
		} catch (SQLException e) {
			response = new Mssg(mssg.getID(),P.error,"login error");
		}
		c.sendToClient(response);
	}
	
	
	private void handleViewRequest(ConnectionToClient c, Mssg mssg) throws IOException {
		User u = usersHash.get(c);
		if (u==null) {
			c.sendToClient(new Mssg(mssg.getID(),P.error,"user is not logged in"));
			return;
		}
		HashMap<String, String> hash = (HashMap<String, String>)mssg.getMessege();
		if (hash.get("key").equals("change request by id")) {
			mssg.setMessege(dc.getRequestDetails(Long.parseLong(hash.get("value"))));
		} else {
			mssg.setMessege(dc.getAllRequestDetails());
		}
		c.sendToClient(mssg);
	}
	
	private void handleCreateRequest(ConnectionToClient c, Mssg mssg) throws IOException {
		User u = usersHash.get(c);
		if (u==null) {
			c.sendToClient(new Mssg(mssg.getID(),P.error,"user is not logged in"));
			return;
		}
		try {
			mssg.setMessege(dc.createRequest((ArrayList<String>) mssg.getMessege()));
		} catch (SQLException e) {
			c.sendToClient(new Mssg(mssg.getID(),P.error,"couldnt create mssg"));
			return;
		}
		c.sendToClient(mssg);
	}
	public static void main(String[] args) throws IOException {
		Server server = new Server(12389);
		server.listen();
	}
}
